package com.android.love.ui;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.android.love.R;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.ImageUtils;
import com.android.love.util.LogUtil;
import com.android.love.util.NetworkUtil;
import com.android.love.vo.Address;
import com.android.love.vo.MyRequest;
import com.android.love.vo.Order;
import com.android.love.vo.OrderId;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class OrderActivity extends BasePageActivity {
	private List<Address> address_list = Collections.emptyList();
	private ViewFinder orderFidler;
	private boolean single;
	// private String default_address;
	private Address address;
	private Order order;
	private String order_id;
	private String[] pay_type = new String[] { "支付宝（推荐）", "银联支付" };
	private String[] express_type = new String[] { "普通快递（免运费）", "其他快递方式" };
	private int channel = 1;
	private int express = 1;
	private AlertDialog singleDialog;
	private EditText et_liuyan;

	private float yunfei;
	private float sum;

	private int pay_id;
	private int express_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 隐藏软键盘
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		View orderView = inflater.inflate(R.layout.activity_order, null);
		orderFidler = new ViewFinder(orderView);
		setContentView(orderView);
		process();
		setListener();
		getData();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.android.love.ui.BasePageActivity#process()
	 */
	@Override
	protected void process() {
		super.process();
		// default_address = sp.getValue("default_address", "");
		address = new Address();
		address.setAddress(sp.getValue("default_address", null));
		address.setAddress_id(sp.getValue("default_address_id", 0l));
		address.setConsignee(sp.getValue("default_consignee", null));
		address.setMail(sp.getValue("default_mail", null));
		address.setPhone(sp.getValue("default_phone", null));
		address.setPostal(sp.getValue("default_postal", null));
		orderFidler.setDrawable(R.id.iv_shuaxin, R.drawable.btn_quxiao);
		hide(orderFidler.find(R.id.iv_top_meinv));
		orderFidler.setText(R.id.top_title, "提交订单");
		if (!TextUtils.isEmpty(sp.getValue("default_consignee", null))) {
			orderFidler.setText(
					R.id.tv_address_text,
					sp.getValue("default_consignee", null) + "  "
							+ sp.getValue("default_phone", null) + "\n"
							+ sp.getValue("default_address", null) + "  "
							+ sp.getValue("default_postal", null));
		} else {
			orderFidler.setText(R.id.tv_address_text, "没有填写收货地址，请新建一个");
		}
		et_liuyan = orderFidler.find(R.id.et_liuyan);
		et_liuyan.clearFocus();
		Intent intent = getCurrentIntent();
		if (intent != null) {
			single = intent.getBooleanExtra("single", false);
			order = (Order) intent.getSerializableExtra("order");
			if (single) {
				// 立即购买进入
				// Goods order = (Goods) intent.getSerializableExtra("order");
				show(orderFidler.find(R.id.rl_single));
				updateSingle(order);
			} else {
				// 购物车进入
				hide(orderFidler.find(R.id.rl_single));
				// float total_price = intent.getFloatExtra("total_price", 0);
				// float yunfei = intent.getFloatExtra("yunfei", 0);
			}
			yunfei = 0;
			sum = order.getSum();
			updateTotalPrice();
		}
	}

	/**
	 * 更新支付清单
	 */
	private void updateTotalPrice() {
		String html_sum_yunfei = "<font color=\"#000000\">" + "应付金额: "
				+ "</font>" + "<font color=\"#e2017b\">" + "￥ "
				+ (sum + yunfei) + "</font>";
		String html_sum = "<font color=\"#000000\">" + "商品总额: " + "</font>"
				+ "<font color=\"#e2017b\">" + "￥ " + sum + "</font>";
		String html_yunfei = "<font color=\"#000000\">" + "运费: " + "</font>"
				+ "<font color=\"#e2017b\">" + "￥ " + yunfei + "</font>";
		orderFidler
				.setText(R.id.tv_total_price, Html.fromHtml(html_sum_yunfei));
		orderFidler.setText(R.id.tv_zhifu_list_text_price,
				Html.fromHtml(html_sum));
		orderFidler.setText(R.id.tv_zhifu_list_text_yunfei,
				Html.fromHtml(html_yunfei));
		order.setSum(sum + yunfei);
	}

	@Override
	protected Boolean loadBottomTab() {
		// TODO Auto-generated method stub
		return false;
	}

	private void updateSingle(final Order order) {
		// TODO Auto-generated method stub
		// hide(orderFidler.find(R.id.rl_zhifu_list));
		// hide(orderFidler.find(R.id.rl_zhifu_list_text));
		// order.getGoods().get(0).setNum(1);
		order.getGoods().get(0).setCount(1);
		loader.displayImageForSize(order.getGoods().get(0).getGoods_image(),
				orderFidler.imageView(R.id.iv_cart_img),
				ImageUtils.getOptions(R.drawable.zw2),
				new SimpleImageLoadingListener(), 8, 0, 0, 0, 0, 0, 5f, true);
		orderFidler.setText(R.id.tv_cart, order.getGoods().get(0)
				.getGoods_name());
		orderFidler.setText(R.id.tv_id, "编号:"
				+ order.getGoods().get(0).getGoods_id());
		orderFidler.setText(R.id.tv_price, "￥"
				+ order.getGoods().get(0).getPrice()
				* order.getGoods().get(0).getCount() + "");
		// orderFidler.setText(R.id.tv_total_price, "应付金额：￥"
		// + order.getGoods().get(0).getPrice()
		// * order.getGoods().get(0).getNum() + "");

		orderFidler.setText(R.id.tv_num, order.getGoods().get(0).getCount()
				+ "");
		StringBuilder sb = new StringBuilder();
		orderFidler.setText(R.id.tv_format, order.getGoods().get(0)
				.getAttribute());
		sum = order.getGoods().get(0).getPrice()
				* order.getGoods().get(0).getCount();
		updateTotalPrice();
		orderFidler.find(R.id.iv_add).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LogUtil.i(TAG, "iv_add");
				int num = order.getGoods().get(0).getCount();
				++num;
				order.getGoods().get(0).setCount(num);
				orderFidler.setText(R.id.tv_num, num + "");
				orderFidler.setText(R.id.tv_price, "￥"
						+ order.getGoods().get(0).getPrice()
						* order.getGoods().get(0).getCount() + "");
				sum = order.getGoods().get(0).getPrice()
						* order.getGoods().get(0).getCount();
				updateTotalPrice();
			}
		});
		orderFidler.find(R.id.iv_reduce).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int num = order.getGoods().get(0).getCount();
						if (num > 1) {
							--num;
							order.getGoods().get(0).setCount(num);
							orderFidler.setText(R.id.tv_num, num + "");
							orderFidler.setText(R.id.tv_price, "￥"
									+ order.getGoods().get(0).getPrice()
									* order.getGoods().get(0).getCount() + "");
							sum = order.getGoods().get(0).getPrice()
									* order.getGoods().get(0).getCount();
							updateTotalPrice();
						}
					}
				});
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		super.setListener();
		orderFidler.find(R.id.iv_shuaxin).setOnClickListener(this);
		orderFidler.find(R.id.iv_tijiao).setOnClickListener(this);
		orderFidler.find(R.id.rl_zhifu).setOnClickListener(this);
		orderFidler.find(R.id.rl_kuaidi).setClickable(false);
		orderFidler.find(R.id.iv_newAddress).setOnClickListener(this);
		orderFidler.find(R.id.tv_address_text).setOnClickListener(this);
		orderFidler.find(R.id.iv_kefu).setOnClickListener(this);
	}

	@Override
	protected void getData() {
		// TODO Auto-generated method stub
		super.getData();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_kefu:
			showPopupWindow(orderFidler.find(R.id.iv_kefu), 2);
			break;
		case R.id.iv_shuaxin:
			finish();
			overridePendingTransition(R.anim.slide_up_in, R.anim.slide_down_out);
			break;
		case R.id.tv_address_text:
			MyRequest req = new MyRequest();
			req.authority = UriHelper.REALM_NAME;
			req.path = UriHelper.URL_ADDRESS_LIST;
			req.paramers = generateParams(1);
			getDataFromTask(context, ADDRESS_LIST, req, address_list, true,
					false);
			// finish();
			// overridePendingTransition(R.anim.slide_up_in,
			// R.anim.slide_down_out);
			break;
		case R.id.iv_newAddress:
			// 创建默认地址
			Intent nIntent = new Intent(context, AddressActivity.class);
			nIntent.putExtra("new_address", true);
			startActivityForResult(nIntent, ADDRESS_ADD);
			break;
		case R.id.rl_zhifu:
			singleDialog = new AlertDialog.Builder(context)
					.setTitle("支付方式")
					.setSingleChoiceItems(pay_type, pay_id,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									pay_id = which;
									channel = which + 1;
									orderFidler.setText(R.id.tv_zhifu, "支付方式："
											+ pay_type[which]);
									singleDialog.dismiss();
								}
							}).create();
			singleDialog.show();
			break;
		case R.id.rl_kuaidi:
			singleDialog = new AlertDialog.Builder(context)
					.setTitle("快递方式")
					.setSingleChoiceItems(express_type, express_id,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									switch (which) {
									case 0:
										express_id = 0;
										yunfei = 0;
										break;
									case 1:
										express_id = 1;
										yunfei = 10;
										break;

									default:
										break;
									}
									updateTotalPrice();
									express = which + 1;
									orderFidler.setText(R.id.tv_kuaidi, "快递方式："
											+ express_type[which]);
									singleDialog.dismiss();
								}
							}).create();
			singleDialog.show();
			break;
		case R.id.iv_tijiao:
			// finish();
			if (TextUtils.isEmpty(orderFidler.textView(R.id.tv_address_text)
					.getText().toString().trim())) {
				// 创建默认地址
				ActivityUtil.show(OrderActivity.this, "请添加地址");
				Intent intent = new Intent(context, AddressActivity.class);
				intent.putExtra("new_address", true);
				startActivityForResult(intent, ADDRESS_ADD);
			} else {
				// 提交
				if (NetworkUtil.isAvailable(context)) {
					MyRequest tReq = new MyRequest();
					tReq.authority = UriHelper.REALM_NAME;
					tReq.path = UriHelper.URL_ORDER;
					tReq.paramers = generateParams();
					String[] orderid = null;
					getDataFromTask(context, TIJIAO, tReq, orderid, true, false);
				} else {
					ActivityUtil.show(OrderActivity.this, "网络错误");
				}
			}
			break;

		default:
			break;
		}
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams() {
		JSONObject json = new JSONObject();
		String goods = JSON.toJSONString(order.getGoods());
		LogUtil.i(TAG, "goods--" + goods);
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		params.put("goods", goods);
		params.put("channel", channel + "");
		params.put("express", express + "");
		params.put("consignee", address.getConsignee());
		params.put("address", address.getAddress());
		params.put("phone", address.getPhone());
		params.put("mail", address.getMail());
		params.put("postal", address.getPostal());
		params.put("msg", et_liuyan.getText().toString().trim());
		params.put("sum", order.getSum() + "");
		if (sp.getValue(USER_ID, 0) != 0)
			params.put("user_id", sp.getValue(USER_ID, 0) + "");
		if (!"".equals(sp.getValue(SIG, "")))
			params.put("sig", sp.getValue(SIG, ""));
		return params;
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == ADDRESS_ADD) {
			if (arg2 != null) {
				address = (Address) arg2.getSerializableExtra("address_add");
				if (address != null) {
					if (TextUtils.isEmpty(sp
							.getValue("default_consignee", null))) {
						sp.setValue("default_address", address.getAddress());
						sp.setValue("default_address_id",
								address.getAddress_id());
						sp.setValue("default_consignee", address.getConsignee());
						sp.setValue("default_mail", address.getMail());
						sp.setValue("default_phone", address.getPhone());
						sp.setValue("default_postal", address.getPostal());
					}
					orderFidler.setText(R.id.tv_address_text,
							address.getConsignee() + "  " + address.getPhone()
									+ "\n" + address.getAddress() + "  "
									+ address.getPostal());
				}
			}
		}
	}

	@Override
	public void handle(int tag, Object object) {
		super.handle(tag, object);
		switch (tag) {
		case TIJIAO:
			if (object != null) {
				if ((String[]) object != null) {
					ActivityUtil.show(OrderActivity.this, "订单提交成功");
					String[] ids = (String[]) object;
					order_id = ids[0];
					String trade_no = ids[1];
					order.setOrder_id(order_id);
					order.setTrade_no(trade_no);
					order.setChannel(channel);
					order.setExpress(express);
					order.setConsignee(address.getConsignee());
					order.setAddress(address.getAddress());
					order.setPhone(address.getPhone());
					order.setMail(address.getMail());
					order.setPostal(address.getPostal());
					order.setMsg(et_liuyan.getText().toString().trim());
					order.setSum(order.getSum());
					// order.setSum(0.01f);
					order.setGoods(order.getGoods());
					order.setStatus(1);
					Intent intent = new Intent();
					intent.putExtra("result", true);
					intent.putExtra("order", order);
					setResult(0, intent);
					int order_num = sp.getValue(ORDER_NUM, 0);
					sp.setValue(ORDER_NUM, ++order_num);
					updateBottomOrder();
					finish();
					overridePendingTransition(R.anim.slide_up_in,
							R.anim.slide_down_out);

					// order.setSum(order_num)

					// params.put("channel", channel + "");
					// params.put("express", express + "");
					// params.put("consignee", address.getConsignee());
					// params.put("address", address.getAddress());
					// params.put("phone", address.getPhone());
					// params.put("mail", address.getMail());
					// params.put("postal", address.getPostal());
					// params.put("msg", et_liuyan.getText().toString().trim());
					// params.put("sum", order.getSum() + "");
					// if (sp.getValue(USER_ID, 0) != 0)
					// params.put("user_id", sp.getValue(USER_ID, 0) + "");
					// if (!"".equals(sp.getValue(SIG, "")))
					// params.put("sig", sp.getValue(SIG, ""));
					// return params;
				}
			}

			break;
		case ADDRESS_LIST:
			if (object != null) {
				address_list = (List<Address>) object;
				if (address_list.size() == 0) {
					// 新建地址
					ActivityUtil.show(OrderActivity.this, "没地址列表，请创建一个");
					Intent nIntent = new Intent(context, AddressActivity.class);
					nIntent.putExtra("new_address", true);
					startActivityForResult(nIntent, ADDRESS_ADD);
				} else {
					// 选择地址
					// String[] address_type = null;
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < address_list.size(); i++) {
						if (i < address_list.size() - 1) {
							sb.append(address_list.get(i).getAddress()).append(
									",");
						} else {
							sb.append(address_list.get(i).getAddress());
						}
					}
					singleDialog = new AlertDialog.Builder(context)
							.setTitle("地址选择")
							.setSingleChoiceItems(sb.toString().split(","), 0,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											address = address_list.get(which);
											orderFidler
													.setText(
															R.id.tv_address_text,
															address.getConsignee()
																	+ "  "
																	+ address
																			.getPhone()
																	+ "\n"
																	+ address
																			.getAddress()
																	+ "  "
																	+ address
																			.getPostal());
											// express = which;
											// orderFidler
											// .setText(
											// R.id.tv_kuaidi,
											// "快递方式："
											// + express_type[which]);
											singleDialog.dismiss();
										}
									}).create();
					singleDialog.show();
				}
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			overridePendingTransition(R.anim.fade, R.anim.slide_down_out);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams(int page) {
		JSONObject json = new JSONObject();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		params.put("page", page + "");
		params.put("count", "10");
		if (sp.getValue(USER_ID, 0) != 0)
			params.put("user_id", sp.getValue(USER_ID, 0) + "");
		if (!"".equals(sp.getValue(SIG, "")))
			params.put("sig", sp.getValue(SIG, ""));
		return params;
	}

}
